package com.zimin.cloud.system.service.impl;

import cn.hutool.core.lang.Opt;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zimin.cloud.mine.pojo.system.view.AccountVO;
import com.zimin.cloud.mine.pojo.system.view.MenuVO;
import com.zimin.cloud.mine.pojo.system.view.RoleVO;
import com.zimin.cloud.system.mapper.RoleMenuMapper;
import com.zimin.cloud.system.pojo.entity.AccountRole;
import com.zimin.cloud.system.pojo.entity.Menu;
import com.zimin.cloud.system.pojo.entity.RoleMenu;
import com.zimin.cloud.system.service.IAccountRoleService;
import com.zimin.cloud.system.service.IMenuService;
import com.zimin.cloud.system.service.IRoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单关联表 服务实现类
 * </p>
 *
 * @author zimin
 * @since 2021-12-30 11:05
 */
@Service("roleMenuService")
@Slf4j
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    @Autowired
    private IAccountRoleService accountRoleService;
    @Autowired
    private IMenuService menuService;


    @Override
    public boolean removeByRoleId(String roleId) {
        return remove(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleId));
    }

    @Override
    public boolean removeByRoleIds(Collection<? extends Serializable> roleIdList) {
        return remove(Wrappers.<RoleMenu>lambdaQuery().in(RoleMenu::getRoleId, roleIdList));
    }

    @Override
    public List<String> getMenuIdByRoleId(Serializable roleId) {
        var roleMenus = list(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleId));
        if (ObjectUtils.isEmpty(roleMenus)) {
            return List.of();
        }
        return roleMenus.parallelStream().map(RoleMenu::getMenuId).distinct().collect(Collectors.toList());
    }

    @Override
    public List<String> getMenuPermissions(String accountId) {
        var accountRoles = accountRoleService.listByAccountId(accountId);
        var roleIds = accountRoles.parallelStream().map(AccountRole::getRoleId).collect(Collectors.toSet());
        // TODO：校验是否包含admin权限
        if (ObjectUtils.isEmpty(roleIds)) {
            return List.of();
        }
        var menuList = menuService.getMenuPermissionsByRoleIds(roleIds);
        return menuList.parallelStream().map(MenuVO::getPerms).filter(StringUtils::isNotBlank).collect(Collectors.toList());
    }
}
